import { Link, useNavigate } from 'react-router-dom'
import {
  Table,
  Space,
  Tag,
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Popconfirm,
  message,
} from 'antd'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import img404 from '@/assets/error.png'
// import TableTo from './Table'
import type { ColumnsType } from 'antd/es/table'
// moment国际化
// import 'moment/locale/zh-cn'
// 局内组件国际化
// import locale from 'antd/es/date-picker/locale/zh_CN'
import {
  getArticleAction,
  Params,
  delArticleAction,
} from '@/store/actions/article'
import { ArticleList } from '@/store/modules/article'
import { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { AppDispatch, RootState } from '@/store'
import { Moment } from 'moment'
import Channel from '@/components/channel'
const { RangePicker } = DatePicker
// enum Aa {
//   0 = 1,
// }
// 优化文章状态的处理
type ArticleStatus = {
  color?: string
  text?: string
}
const articleStatus: Record<number | string, ArticleStatus> = {
  0: { color: 'yellow', text: '草稿' },
  1: { color: '#ccc', text: '待审核' },
  2: { color: 'green', text: '审核通过' },
  3: { color: 'red', text: '审核失败' },
}

const Article = () => {
  const dispatch = useDispatch<AppDispatch>()
  const searchParams = useRef<Params>({})
  const navigate = useNavigate()
  // 获取文章列表和channel数据
  useEffect(() => {
    dispatch(getArticleAction({}))
  }, [dispatch])
  // 分页功能
  const {
    articleList,
    query: { total_count, page, per_page },
  } = useSelector((state: RootState) => state.article)
  // 点解页面或切换条数 都会触发
  const changePage = (page: number, pageSize: number) => {
    // console.log(page, pageSize)
    // { page, per_page: pageSize }
    searchParams.current = { ...searchParams.current, page, per_page: pageSize }
    // console.log('searchParams', searchParams.current)
    dispatch(
      getArticleAction({
        // 将筛选出来的条件先解构出来
        ...searchParams.current,
        page,
        per_page: pageSize,
      })
    )
  }
  // 搜索函数
  const search = ({
    status,
    channel_id,
    date,
  }: {
    status?: number
    channel_id?: number
    date?: Moment[]
  }) => {
    // 组装查询对象
    const params = {
      channel_id,
      begin_pubdate: '',
      end_pubdate: '',
    } as Params

    // 排除全部
    if (status !== -1 && status) {
      params.status = status
    }
    // 格式化时间对象
    // 判断是否选择时间
    if (!!date) {
      params.begin_pubdate = date[0].format('YYYY-MM-DD')
      params.end_pubdate = date[1].format('YYYY-MM-DD')
    }
    console.log(params)
    searchParams.current = { ...searchParams.current, ...params }
    // console.log('searchParams666', searchParams.current)
    dispatch(getArticleAction(searchParams.current))
  }
  // 删除文章
  const confirm = async (id: string) => {
    console.log(id)
    await dispatch(delArticleAction(id))
    await dispatch(getArticleAction(searchParams.current))
    message.success('删除文章成功')
  }
  // 组件列 配置项 ：
  const columns: ColumnsType<ArticleList> = [
    {
      title: '封面',
      dataIndex: 'cover',
      /**
       * 指定了dataIndex情况
       * @param {*} cover dataIndex指定字段的值
       * @param {*} row 当前行
       * @param {*} index 索引
       * @returns
       */
      render: (cover, row, index) => {
        // console.log('cover', cover)
        return (
          <img
            src={cover.images[0] || img404}
            width={200}
            height={150}
            alt=""
          />
        )
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220,
    },
    {
      title: '状态',
      dataIndex: 'status',
      // 文章状态，0-草稿，1-待审核，2-审核通过，3-审核失败
      render: (data: number) => {
        // console.log('data', data)
        return (
          <Tag color={articleStatus[data].color}>
            {articleStatus[data].text}
          </Tag>
        )
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      /**
       * 没有指定dataIndex
       * @param {*} row 当前行
       * @returns
       */
      render: (row) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => {
                navigate('/publish/' + row.id)
              }}
            />
            <Popconfirm
              title="你是否想要删除该片文章"
              onConfirm={() => confirm(row.id)}
              okText="Yes"
              cancelText="No">
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      },
    },
  ]
  return (
    <div>
      {/* 搜索 */}
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}>
        <Form
          initialValues={{ status: -1, channel_id: '推荐' }}
          onFinish={search}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            {/* 没有封装之前 放的Selector组件 在表单下会自动做受控处理 
            如何让自己封装的channel组件自动受控？
            channel组件接收 value + onChange 属性
            */}
            <Channel />
          </Form.Item>

          <Form.Item label="日期" name="date">
            {/* locale={locale} 国际化处理 转中文 */}
            <RangePicker></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      {/* 文章列表 */}
      <Card title={`根据筛选条件共查询到 total 条结果：${total_count}`}>
        {/* rowKey={'id'} 统一指定key属性 */}
        <Table
          rowKey={'id'}
          columns={columns}
          dataSource={articleList}
          pagination={{
            pageSize: per_page,
            current: page,
            total: total_count,
            position: ['topLeft'],
            onChange: changePage,
          }}
        />
      </Card>
    </div>
  )
}

export default Article
